package com.ddf.norman.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ddf.norman.entity.LbBidVo;
import com.ddf.publics.entity.*;
import com.ddf.publics.service.*;
import com.ddf.publics.tool.Constant;
import com.ddf.publics.tool.MoneyFund;
import com.ddf.publics.utils.DatesUtil;
import com.ddf.publics.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @description 散标请求控制器
 * @author norman
 * @date 2020/6/27 15:56
 * @params
 * @return
 */
@Controller
public class looseBidController {
    //注入服务层
    @Autowired
    private LooseBidService looseBidService;
    @Autowired
    private LbBidService lbBidService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private FundService fundService;
    @Autowired
    private PayPwdService payPwdService;

    //注入工具类
    @Autowired
    private Semaphore semaphore;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * @description 请求散标列表页面
     * @author norman
     * @date 2020/7/5 19:11
     * @params []
     * @return java.lang.String
     */
    @GetMapping(value = "looseBid")
    public String looseBid() {
        return "invest/looseBid";
    }

    /**
     * @description 异步请求散标列表数据
     * @author norman
     * @date 2020/7/5 19:11
     * @params []
     * @return java.lang.String
     */
    @ResponseBody
    @GetMapping(value = "getLooseBidData")
    public String getLooseBidData() {
        List<LooseBid> looseBidList = looseBidService.queryAllList();
        JSONArray data = new JSONArray();

        looseBidList.forEach(looseBid -> {
            JSONObject jsonObject = new JSONObject();

            Float apr = looseBid.getApr();
            jsonObject.put("apr",apr + "%");

            jsonObject.put("title",looseBid.getId());

            String timeLimit = looseBid.getMonth();
            jsonObject.put("timeLimit",timeLimit+"月");

            DecimalFormat df = new DecimalFormat("#,###");
            String moneyStr = df.format(looseBid.getMoney());
            jsonObject.put("money",moneyStr+"元");

            Float money = lbBidService.queryMoney(looseBid.getId());

            Float bidMoney = looseBid.getMoney();
            int progress = (int) (money/bidMoney*100);
            jsonObject.put("progress",progress+"");

            jsonObject.put("status",looseBid.getStatus());
            data.add(jsonObject);


        });
        JSONObject result = new JSONObject();
        result.put("code",0);
        result.put("msg","success");
        result.put("count",1000);
        result.put("data",data);
        return result.toString();
    }

    /**
     * @description 请求散标详情页面
     * @author norman
     * @date 2020/7/5 19:12
     * @params [sId, model, principal]
     * @return java.lang.String
     */
    @GetMapping(value = "/looseBidInfo/{sId}")
    public String toLooseBidInfo(@PathVariable("sId") Integer sId, Model model, Principal principal) {
        LooseBid looseBid = looseBidService.queryById(sId);

        Float sumMoney = lbBidService.queryMoney(sId);

        UserInfo myUserInfo = userInfoService.userInfoList(loginService.queryByPhone(principal.getName()).getId());

        Integer uId = looseBid.getUId();
        UserInfo userInfo = userInfoService.userInfoList(uId);

        User user = userService.queryById(looseBid.getUId());
        List<LbBid> lbBidList = lbBidService.queryAllBylId(looseBid.getId());
        List<LbBidVo> lbBidMap = new ArrayList<>();
        lbBidList.forEach(lbBid -> {
            LbBidVo lbBidVo = new LbBidVo();

            UserInfo bidUser = userInfoService.userInfoList(lbBid.getBidUserId());
            String userName = bidUser.getRealName().substring(0,1)+ "*" + bidUser.getRealName().substring(bidUser.getRealName().length() -1);
            lbBidVo.setUserName(userName);
            lbBidVo.setMoney(lbBid.getBidMoney());
            lbBidVo.setBidDate(lbBid.getBidDate());
            lbBidMap.add(lbBidVo);
        });
        if (looseBid.getStatus() == Constant.LOOSEBID_STATUS_FULL_MARK) {
            model.addAttribute("bdMonth",DatesUtil.getMonth(looseBid.getValueDate(),Integer.valueOf(looseBid.getMonth())));
            model.addAttribute("nextRepayment",DatesUtil.getRepaymentDate(looseBid.getValueDate()));
        }

        model.addAttribute("looseBid",looseBid);
        model.addAttribute("user",user);
        model.addAttribute("userInfo",userInfo);
        model.addAttribute("myUserInfo",myUserInfo);
        model.addAttribute("sumMoney",sumMoney);
        model.addAttribute("lbBidMap",lbBidMap);
        return "invest/looseBidInfo";
    }

    /**
     * @description 投资散标的请求
     * @author norman
     * @date 2020/7/5 19:13
     * @params [payPwd, money, lbId, principal]
     * @return java.lang.String
     */
    @ResponseBody
    @PostMapping(value = "/loanLooseBid")
    public String  loanLooseBid(String payPwd, Float money,Integer lbId, Principal principal) {

        JSONObject jsonObject = new JSONObject();

        User user = loginService.queryByPhone(principal.getName());
        LooseBid looseBid = looseBidService.queryById(lbId);

        int pwdResult = payPwdService.payPwd(user.getId(),payPwd);

        if (pwdResult == Constant.PAY_NO) {
            jsonObject.put("status","error");
            jsonObject.put("msg","支付密码错误");
            return jsonObject.toJSONString();
        } else if (pwdResult == Constant.PAY_LOCK) {
            jsonObject.put("status","error");
            jsonObject.put("msg","账户被锁定 请明天在试");
            return jsonObject.toJSONString();
        } else if (money == null || money < 50) {
            jsonObject.put("status","error");
            jsonObject.put("msg","出借金额必须试50的倍数");
            return jsonObject.toJSONString();
        }

        try {
            semaphore.acquire();
            Float lbMoney = looseBid.getMoney() - lbBidService.queryMoney(looseBid.getId());

            if (money <= lbMoney) {//如果散标的剩余金额是否足够

                UserInfo userInfo = userInfoService.userInfoList(user.getId());
                if (money > userInfo.getMoney()) {//判断用户余额是否足够
                    jsonObject.put("status","error");
                    jsonObject.put("msg","余额不足");
                }else {
                    //插入投标记录表数据
                    LbBid lbBid = new LbBid();
                    lbBid.setSId(looseBid.getId());
                    lbBid.setBidUserId(user.getId());
                    lbBid.setBidMoney(money);
                    lbBid.setBidDate(new Date());
                    lbBidService.insert(lbBid);

                    //更改用户余额
                    UserInfo ui = new UserInfo();
                    ui.setUfId(userInfo.getUfId());
                    ui.setMoney(userInfo.getMoney() - money);
                    userInfoService.update(ui);

                    //插入资金记录表数据
                    Fund fund = new Fund();
                    fund.setFundAmunt(money);
                    fund.setUId(user.getId());
                    fund.setFundPost(MoneyFund.FUND_INVEST);//投资
                    fundService.insert(fund);

                    if (money.equals(lbMoney)) {
                        //改变散标状态
                        LooseBid looseBidNew = new LooseBid();
                        looseBidNew.setId(looseBid.getId());
                        looseBidNew.setStatus(Constant.LOOSEBID_STATUS_FULL_MARK);
                        looseBidNew.setValueDate(new Date());
                        looseBidService.update(looseBidNew);

                        //设置自动回款
                        for (int i = 1; i <= Integer.valueOf(looseBid.getMonth()); i++) {
                            redisUtil.set("looseBid:" + looseBid.getId()+","+i, "looseBid", i * 30 * 24 * 60 * 60);
                        }
                    }

                    jsonObject.put("status","success");
                    jsonObject.put("msg","成功");
                }
            } else {
                //如果不够，则询问是否继续借出剩余金额
                jsonObject.put("status","warning");
                jsonObject.put("msg","本标剩余金额不足");
                jsonObject.put("money",lbMoney);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            semaphore.release();
        }
        return jsonObject.toJSONString();
    }
}
